package com.ywb.ex02;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.*;

public class Task2 extends JFrame implements ActionListener {

    private JTextField phonetextField; // 创建文本框组件
    private JTextField emailtextField;
    private JTextField nametextField;
    private String imagePath = "";
    private File imageFile;
    private JLabel imageLabel = new JLabel();
    private ImageIcon imageIcon;
    final JPanel panel = new JPanel(); // 创建面板组件
    JMenu fileMenu; // 定义菜单对象
    JMenuItem reveal;
    JMenuItem kinescope;
    JPanel jPanel = new JPanel();
    File file = new File("D://addressList2.txt"); // 创建文件对象
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    Task2 frame = new Task2(); // 创建本类对象
                    frame.setVisible(true); // 设置窗体可视状态
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public Task2() { // 构造方法中实现窗体布局
        super();
        setTitle("个人通讯录"); // 设置窗体标题
        getContentPane().setLayout(null); // 设置窗体布局
        setBounds(100, 100, 500, 350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JMenuBar bar = new JMenuBar();
        fileMenu = new JMenu("文件");
        reveal = new JMenuItem("显示");
        kinescope = new JMenuItem("录入");
        reveal.addActionListener(this);
        kinescope.addActionListener(this);
        this.setJMenuBar(bar);
        bar.add(fileMenu);
        fileMenu.add(reveal);
        fileMenu.add(kinescope);

        panel.setLayout(null);
        panel.setBounds(0, 0, 500, 350);
        getContentPane().add(panel);

        final JLabel namelabel = new JLabel();
        namelabel.setBounds(77, 29, 66, 18);
        namelabel.setText("输入姓名：");
        panel.add(namelabel);

        nametextField = new JTextField();
        nametextField.setBounds(149, 27, 122, 22);
        panel.add(nametextField);

        final JLabel emaillabel = new JLabel();
        emaillabel.setBounds(77, 66, 66, 18);
        emaillabel.setText("输入Email:");
        panel.add(emaillabel);

        emailtextField = new JTextField();
        emailtextField.setBounds(149, 64, 122, 22);
        panel.add(emailtextField);

        final JLabel phonelabel = new JLabel();
        phonelabel.setText("输入电话：");
        phonelabel.setBounds(77, 103, 66, 18);
        panel.add(phonelabel);

        phonetextField = new JTextField();
        phonetextField.setBounds(149, 101, 122, 22);
        panel.add(phonetextField);

        final JLabel label = new JLabel();
        label.setText("单击录入：");
        label.setBounds(77, 137, 66, 18);
        panel.add(label);

        final JButton kinbutton = new JButton();
        kinbutton.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                kinbuttonActionPerformed(e);

            }
        });
        kinbutton.setText("录入");
        kinbutton.setBounds(149, 132, 122, 28);
        panel.add(kinbutton);

        final JButton chooserButton = new JButton();
        chooserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                do_choosenButton_actionPerformed(e);
            }
        });
        chooserButton.setBounds(300, 132, 61, 28);
        chooserButton.setText("选择");
        panel.add(chooserButton);

        imageLabel.setBounds(300, 20, 100, 100);
        imageLabel.setBorder(new LineBorder(Color.BLACK));
        panel.add(imageLabel);

    }
    protected void do_choosenButton_actionPerformed(ActionEvent e){
        JFileChooser fc = new JFileChooser("D:\\100 - 学习\\110 - 编程语言类\\116 - Java开发进阶\\实验4\\img");
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setMultiSelectionEnabled(false);
        fc.setFileFilter(new FileNameExtensionFilter("图片", new String[]{"png", "jpg"}));
        int reVal = fc.showOpenDialog(this);
        if(reVal == JFileChooser.APPROVE_OPTION){
            imagePath = fc.getSelectedFile().getPath();
        }
        imageIcon = new ImageIcon(imagePath);
        //使用选择器加载图片的时候要调用此方法;
        imageIcon.setImage(imageIcon.getImage().getScaledInstance(100,100,Image.SCALE_DEFAULT));
        imageLabel.setIcon(imageIcon);
    }

    private void kinbuttonActionPerformed(ActionEvent evt) {
        try {
            if(nametextField.getText().equals("") || emailtextField.getText().equals("") ||
                    phonetextField.getText().equals("") || imageLabel.getIcon() == null || imageLabel.getIcon().equals("")){
                JOptionPane.showMessageDialog(this, "请把数据输入完整","提示",JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (file.exists()) {
                file.createNewFile();
            }
            PrintWriter pw = new PrintWriter(new FileWriter(file,true));
            pw.write("姓名:" + nametextField.getText() + "\tEmail:" + emailtextField.getText() + "\t电话:" + phonetextField.getText() + "\t头像:" + imagePath + "\n");
            pw.close();
            JOptionPane.showMessageDialog(this, "录入成功!");
        }catch (IOException ie) {
            ie.printStackTrace();
        }finally {
            nametextField.setText("");
            emailtextField.setText("");
            phonetextField.setText("");
            imageLabel.setIcon(null);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == reveal) { // 如果用户单击的是显示菜单项
            try {
                panel.setVisible(false);
                setSize(600,350);
                jPanel = new JPanel();
                jPanel.setLayout(new BorderLayout());
                jPanel.setBounds(0, 0, 600, 350);
                JScrollPane jsp = new JScrollPane();
                JTable table = new JTable(new DefaultTableModel(){
                    public Class getColumnClass(int c){
                        return getValueAt(0, c).getClass();
                    }
                });
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                model.setColumnIdentifiers(new String[]{"姓名", "邮箱", "电话", "头像"});
                jsp.setViewportView(table);
                getContentPane().add(jPanel,BorderLayout.CENTER);
                jPanel.add(jsp,BorderLayout.CENTER);

                BufferedReader in = new BufferedReader(new FileReader(file)); // 创建BufferedReader
                // 对象
                String line = "";
                //姓名:123	Email:qwe	电话:123123	头像:D:\100 - 学习\110 - 编程语言类\116 - Java开发进阶\实验4\img\2.jpg
                while ((line = in.readLine()) != null) { // 循环从文件中读数据
                    String[] div = line.split("[头像|姓名|Email|电话]:|\t");
                    model.addRow(new Object[]{div[1],div[3], div[5], changeImage(new ImageIcon(div[7]), 150, 150)});
                }
                table.setModel(model);
                table.setRowHeight(150);
                in.close();
                repaint();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if (e.getSource() == kinescope) { // 如果用户单击录入菜单项
            getContentPane().remove(jPanel); // 将面板移除窗体
            panel.setVisible(true);
            repaint(); // 窗体重绘
        }
    }
    public ImageIcon changeImage(Icon icon, int x, int y){
        BufferedImage tag = new BufferedImage(x, y,BufferedImage.TYPE_INT_ARGB);
        tag.getGraphics().drawImage(((ImageIcon) icon).getImage(), 0, 0, x, y, null);
        return new ImageIcon(tag);
    }
}

